package ServletContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downloadServlet")
public class ServletDownloadDemo04 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      /*
        文件下载的步骤:
           1: 定义页面,编辑超链接href属性,指向Servlet,传递资源名称filename
           2: 定义Servlet
               1: 获取文件名称
               2: 使用字节输入流加载文件进内存
               3: 指定response的响应头: content-disposition:attachment;filename=xxx
               4: 将数据写出到response输出流
      */
        //1:获取请求参数,也就是文件名称
        String aa = req.getParameter("filename");
        //2:使用字节输入流加载文件进内存
         //2.1:找到文件服务器路径
        ServletContext bb = this.getServletContext();
        String cc = bb.getRealPath("/img/"+aa);
        //2.2用字节流关联
        FileInputStream dd=new FileInputStream(cc);//这时候只是将数据写入到了内存中,还需要将数据从内存中写到控制台上

        //3:设置response的响应头
        //3.1设置响应头类型:content-type
        String ee = bb.getMimeType("filename");
        resp.setHeader("content-type",ee);
        //3.2设置响应头的打开方式为:content-disposition
        resp.setHeader("content-disposition","attachment;filename="+aa);//"filename="这个值为我们下载文件的名字
        //4:将输入流的数据写到输出流中
        ServletOutputStream mm = resp.getOutputStream();
        byte[] nn=new byte[1024 * 6];
        int len;
        while((len =dd.read(nn))!=-1){
            mm.write(nn,0,len);
        }
        dd.close();

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
